// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
  // 身份证特殊配置
  isIdCard?: boolean; // 是否为身份证上传
  idCardType?: "front" | "back"; // 身份证类型：正面或反面
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "image-upload" | "file-upload" | "readonly";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 访客信息表单配置
export const visitorFormConfig: Record<string, FieldConfig> = {
  // 1. 访客基本信息
  name: {
    key: "name",
    label: "姓名",
    type: "input",
    placeholder: "请输入姓名",
    required: true,
    maxlength: 20,
    showInCreate: true,
    showInEdit: true,
  },
  phone: {
    key: "phone",
    label: "手机号",
    type: "input",
    placeholder: "请输入手机号",
    required: true,
    inputType: "number",
    maxlength: 11,
    pattern: "^1[3-9]\\d{9}$",
    patternErrorMessage: "请输入正确的手机号码格式",
    showInCreate: true,
    showInEdit: true,
  },
  idCardNo: {
    key: "idCardNo",
    label: "身份证号",
    type: "input",
    placeholder: "请输入身份证号",
    required: true,
    maxlength: 18,
    pattern: "/(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)/",
    patternErrorMessage: "请输入正确的身份证号码",
    showInCreate: true,
    showInEdit: true,
    validation: (value: any) => {
      if (!value) return { valid: false, message: "请输入身份证号" };
      const pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      return pattern.test(value)
        ? true
        : { valid: false, message: "请输入正确的身份证号码" };
    },
  },
  company: {
    key: "company",
    label: "所属单位/公司",
    type: "input",
    placeholder: "请输入所属单位或公司",
    maxlength: 50,
    showInCreate: true,
    showInEdit: true,
  },
  carNo: {
    key: "carNo",
    label: "车牌号",
    type: "input",
    maxlength: 10,
    placeholder: "请输入车牌号",
    required: false,
    showInCreate: true,
    showInEdit: true,
    pattern: "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$",
    patternErrorMessage: "请输入正确的车牌号码格式",
    validation: (value: any) => {
      if (!value) return true; // 非必填
      const pattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/;
      return pattern.test(value)
        ? true
        : { valid: false, message: "请输入正确的车牌号码格式" };
    },
  },
  user: {
    key: "user",
    label: "绑定用户",
    type: "picker",
    placeholder: "请选择绑定用户",
    required: false,
    showInCreate: true,
    showInEdit: true,
    options: [], // 从API动态获取
    optionsData: [], // 选项数据
  },
  remark: {
    key: "remark",
    label: "备注信息",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
  },

  // 2. 身份信息
  idCardFrontPhoto: {
    key: "idCardFrontPhoto",
    label: "身份证正面照片",
    type: "image-upload",
    placeholder: "请上传身份证正面照片",
    required: false,
    showInCreate: true,
    showInEdit: true,
    fileConfig: {
      accept: "image",
      maxSize: 3, // 3MB
      maxCount: 1,
      listType: "picture-card",
      uploadUrl: "/api/upload/idcard",
      tips: "请确保身份证正面照片清晰完整，无反光、遮挡",
      // 身份证特殊标识
      isIdCard: true,
      idCardType: "front"
    },
  },
  idCardBackPhoto: {
    key: "idCardBackPhoto",
    label: "身份证反面照片",
    type: "image-upload",
    placeholder: "请上传身份证反面照片",
    required: false,
    showInCreate: true,
    showInEdit: true,
    fileConfig: {
      accept: "image",
      maxSize: 3, // 3MB
      maxCount: 1,
      listType: "picture-card",
      uploadUrl: "/api/upload/idcard",
      tips: "请确保身份证反面照片清晰完整，无反光、遮挡",
      // 身份证特殊标识
      isIdCard: true,
      idCardType: "back"
    },
  },

  // 3. 黑名单信息
  blackStatus: {
    key: "blackStatus",
    label: "黑名单状态",
    type: "picker",
    placeholder: "请选择黑名单状态",
    required: false,
    showInCreate: true,
    showInEdit: true,
    options: ["正常", "黑名单"],
    optionsData: [
      { value: "false", text: "正常" },
      { value: "true", text: "黑名单" },
    ],
  },
  blackReason: {
    key: "blackReason",
    label: "黑名单原因",
    type: "textarea",
    placeholder: "请输入黑名单原因",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
  },
};

// 表单分组配置
export const formSections: FormSection[] = [
  {
    key: "visitorBasicInfo",
    title: "访客基本信息",
    fields: [
      visitorFormConfig.name,
      visitorFormConfig.phone,
      visitorFormConfig.idCardNo,
      visitorFormConfig.company,
      visitorFormConfig.carNo,
      visitorFormConfig.user,
      visitorFormConfig.remark,
    ],
  },
  {
    key: "identityInfo",
    title: "身份信息",
    fields: [
      visitorFormConfig.idCardFrontPhoto,
      visitorFormConfig.idCardBackPhoto,
    ],
  },
  {
    key: "blacklistInfo",
    title: "黑名单信息",
    fields: [
      visitorFormConfig.blackStatus,
      visitorFormConfig.blackReason,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  return formSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      } else if (pageType === 'details') {
        // 详情页根据showInDetails配置显示字段
        return field.showInDetails !== false;
      }
      return false;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(visitorFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};